package com.sk.sourcecircle.activity.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.main.MainActivity;
import com.sk.sourcecircle.app.MyApplication;
import com.sk.sourcecircle.base.BaseFragment;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.callback.MyCallBack;
import com.sk.sourcecircle.common.Constants;
import com.sk.sourcecircle.entity.QQEntity;
import com.sk.sourcecircle.entity.UserInfo;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SPUtils;
import com.sk.sourcecircle.view.VerificationCodeButton;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by sk on 2017/11/28.
 */

public class LoginFragment extends BaseFragment implements HandleDataCallBack {
    @BindView(R.id.ed_account)
    EditText edAccount;
    @BindView(R.id.ed_password)
    EditText edPassword;
    @BindView(R.id.get_code)
    VerificationCodeButton getCode;
    @BindView(R.id.login)
    TextView login;
    @BindView(R.id.wx_ll)
    TextView wxLl;
    @BindView(R.id.qq_ll)
    TextView qqLl;
    @BindView(R.id.weibo_ll)
    TextView weiboLl;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.to_visiable)
    ImageView toVisiable;
    @BindView(R.id.to_invisiable)
    ImageView toInvisiable;
    Unbinder unbinder;

    private String weixinCode = "";
    public static IWXAPI WXapi;
    private LoadingDialog loadingDialog;
    private String myCookie;
    private boolean isSendCode = false;
    private String phone = "";
    private Tencent mTencent;

    private MyCallBack myCallBack;

    public MyCallBack getMyCallBack() {
        return myCallBack;
    }

    public void setMyCallBack(MyCallBack myCallBack) {
        this.myCallBack = myCallBack;
    }

    @Override
    protected int getContentView() {
        return R.layout.fragment_login;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        edAccount.setText(MyUtils.getMobile(mContext));
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
    }

    @OnClick({R.id.get_code, R.id.login, R.id.wx_ll, R.id.qq_ll, R.id.weibo_ll, R.id.to_visiable, R.id.to_invisiable, R.id.forget_password})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.get_code:

                if (!TextUtils.isEmpty(edAccount.getText().toString()) && edAccount.getText().toString().startsWith("1") && edAccount.getText().toString().length() == 11) {
                    getCode.startTimer();
                    loadingDialog.show();
                    phone = edAccount.getText().toString();
                    AppApi.sendCode(edAccount.getText().toString(), 17, LoginFragment.this, 1, getActivity());
                } else {
                    Toast.makeText(mContext, "请输入手机号!", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.login:
                List<EditText> editTexts = new ArrayList<>();
                edAccount.setTag("请输入您的账号!");
                edPassword.setTag("请输入您的密码！");
                editTexts.add(edAccount);
                editTexts.add(edPassword);
                if (MyUtils.isFormat(mRootView, editTexts)) {
                    loadingDialog.show();
                    SPUtils.put(mContext, "account", edAccount.getText().toString());
                    if (isSendCode && edPassword.getText().toString().length() == 6) {
                        AppApi.codeLogin(edAccount.getText().toString(), edPassword.getText().toString(), MyApplication.getInstance().getLat(), MyApplication.getInstance().getLng(), LoginFragment.this, 0, getActivity());
                    } else {
                        AppApi.accountLogin(edAccount.getText().toString(), edPassword.getText().toString(), MyApplication.getInstance().getLat(), MyApplication.getInstance().getLng(), LoginFragment.this, 0, getActivity());
                    }
                }
                break;
            case R.id.wx_ll:
                WXLogin();
                break;
            case R.id.qq_ll:
                login();
                break;
            case R.id.weibo_ll:
                if (myCallBack != null) {
                    myCallBack.sure();
                }
                break;
            case R.id.to_visiable:
                edPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                toVisiable.setVisibility(View.GONE);
                toInvisiable.setVisibility(View.VISIBLE);
                break;
            case R.id.to_invisiable:
                edPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                toVisiable.setVisibility(View.VISIBLE);
                toInvisiable.setVisibility(View.GONE);
                break;
            case R.id.forget_password:
                Intent intent = new Intent(mContext, ForgetPasswordActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 登录微信
     */
    private void WXLogin() {
//        Toast.makeText(mContext, "login", Toast.LENGTH_SHORT).show();
        WXapi = WXAPIFactory.createWXAPI(mContext, Constants.WX_ID, true);
        WXapi.registerApp(Constants.WX_ID);
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo";
        WXapi.sendReq(req);
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.v("onResume", MyApplication.resp + "");
        if (MyApplication.resp != null) {
            if (MyApplication.resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
                // code返回21
                weixinCode = ((SendAuth.Resp) MyApplication.resp).code;
                loadingDialog.show();
                AppApi.wxLogin(weixinCode, MyApplication.getInstance().getLat(), MyApplication.getInstance().getLng(), LoginFragment.this, 6, getActivity());
                Log.v("weixinCode", weixinCode);
            }
        }
    }

    @Override
    public void handlerSuccessData(String result, int tag) {

        switch (tag) {
            case 0:
                UserInfo userInfo = JSON.parseObject(result, UserInfo.class);
                SPUtils.put(mContext, "userId", userInfo.getData().getUser_id());
                SPUtils.put(mContext, "token", userInfo.getData().getToken());
                SPUtils.put(mContext, "login", result);
                Log.v("login", userInfo.getData().getToken());
                loginHx(userInfo.getData().getHx_login(), userInfo.getData().getHx_pass());

                break;
            case 1:
                loadingDialog.cancelDialog();
                isSendCode = true;
                Toast.makeText(mContext, "验证码发送成功！", Toast.LENGTH_SHORT).show();
                break;
            case 6:

                //微信登录
                UserInfo userInfo1 = JSON.parseObject(result, UserInfo.class);
                SPUtils.put(mContext, "userId", userInfo1.getData().getUser_id());
                SPUtils.put(mContext, "token", userInfo1.getData().getToken());
                SPUtils.put(mContext, "login", result);
                Log.v("login", userInfo1.getData().getToken());
                if (userInfo1.getData().getPhone() != null && userInfo1.getData().getPhone().length() > 0) {
                    loginHx(userInfo1.getData().getHx_login(), userInfo1.getData().getHx_pass());
                } else {
                    Intent intent = new Intent(mContext, WxInfoActivity.class);
                    intent.putExtra("data", userInfo1.getData());
                    intent.putExtra("type", ((LoginActivity) getActivity()).getType());
                    startActivity(intent);
                    getActivity().finish();
                }
                break;
            case 12:
                //qq登录
                UserInfo userInfo2 = JSON.parseObject(result, UserInfo.class);
                SPUtils.put(mContext, "userId", userInfo2.getData().getUser_id());
                SPUtils.put(mContext, "token", userInfo2.getData().getToken());
                SPUtils.put(mContext, "login", result);
                Log.v("login", userInfo2.getData().getToken());
                if (userInfo2.getData().getPhone() != null && userInfo2.getData().getPhone().length() > 0) {
                    loginHx(userInfo2.getData().getHx_login(), userInfo2.getData().getHx_pass());
                } else {
                    Intent intent = new Intent(mContext, WxInfoActivity.class);
                    intent.putExtra("data", userInfo2.getData());
                    intent.putExtra("type", ((LoginActivity) getActivity()).getType());
                    startActivity(intent);
                    getActivity().finish();
                }
                break;
        }
    }

    private void loginHx(String account, String password) {
        EMClient.getInstance().login(account, password, new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadingDialog.cancelDialog();
                        Toast.makeText(mContext, "登录成功！", Toast.LENGTH_SHORT).show();
                    }
                });
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
//                Toast.makeText(mContext,"登录聊天服务器成功",Toast.LENGTH_SHORT).show();
                Log.d("loginHx", "登录聊天服务器成功！");
                if (getActivity() instanceof LoginActivity) {

                    if (((LoginActivity) getActivity()).getType() == 1) {
                        Intent intent = new Intent(mContext, MainActivity.class);
                        startActivity(intent);
                        getActivity().finish();
                    } else {
                        getActivity().setResult(Activity.RESULT_OK);
                        getActivity().finish();
                    }
                }
            }

            @Override
            public void onProgress(int progress, String status) {


            }

            @Override
            public void onError(int code, String message) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadingDialog.cancelDialog();
                    }
                });
//                Toast.makeText(mContext,"登录聊天服务器失败"+message,Toast.LENGTH_SHORT).show();
                Log.d("loginHx", "登录聊天服务器失败！");
                Log.d("loginHx", message);
                if (getActivity() instanceof LoginActivity) {

                    if (((LoginActivity) getActivity()).getType() == 1) {
                        Intent intent = new Intent(mContext, MainActivity.class);
                        startActivity(intent);
                        getActivity().finish();
                    } else {
                        getActivity().setResult(Activity.RESULT_OK);
                        getActivity().finish();
                    }
                }

            }
        });
    }

    public void login() {
        mTencent = MyApplication.getInstance().getTencent();
        if (!mTencent.isSessionValid()) {
            mTencent.login(this, "all", new BaseUiListener());
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(final Object o) {
            Log.v("BaseUiListener", o.toString());
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    loadingDialog.show();
                    QQEntity qqEntity = JSON.parseObject(o.toString(), QQEntity.class);
                    AppApi.qqLogin(qqEntity.getOpenid(), qqEntity.getAccess_token(), MyApplication.getInstance().getLat(), MyApplication.getInstance().getLng(), LoginFragment.this, 12, getActivity());
                }
            });

        }

        @Override
        public void onError(UiError uiError) {
            Log.v("BaseUiListener", uiError.toString());
        }

        @Override
        public void onCancel() {
            Log.v("BaseUiListener", "cancel");
        }
    }


    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.v("onActivityResult", String.valueOf(requestCode));
//        Tencent.onActivityResultData(requestCode, resultCode, data, new BaseUiListener());
        Tencent.handleResultData(data, new BaseUiListener());

    }
}
